<?php


namespace App\Exceptions\JsonResponse;


use App\Exceptions\Code\ErrorCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Symfony\Component\HttpKernel\Exception\HttpException;

class JsonResponseException extends HttpException
{
    public function __construct(string $message = '', ?int $code = ErrorCode::FAILED, \Throwable $previous = null, array $headers = [])
    {
        parent::__construct(200, $message ?: JsonResponseException::getErrorMessage($code), $previous, $headers, $code);
    }

    /**
     * @param $errCode
     * @return array|\Illuminate\Contracts\Translation\Translator|string|null
     */
    public static function getErrorMessage($errCode)
    {
        return trans('exception.' . $errCode);
    }

    public function render()
    {
        return config('app.debug')
            ? new JsonResponse($this->getExceptionDetailed(), $this->getStatusCode(), $this->getHeaders(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
            : $this->getException();
    }

    /**
     * 详细的异常信息
     * @return array
     */
    protected function getExceptionDetailed()
    {
        return [
            'errcode' => $this->getCode(),
            'errmsg' => $this->getMessage(),
            'exception' => get_class($this),
            'file' => $this->getFile(),
            'line' => $this->getLine(),
            'trace' => collect($this->getTrace())->map(function ($trace) {
                return Arr::except($trace, ['args']);
            })->all(),
        ];
    }

    /**
     * 异常信息
     * @return array
     */
    protected function getException()
    {
        return [
            'errcode' => $this->getCode(),
            'errmsg' => $this->getMessage(),
        ];
    }
}